﻿/**
 * @author Colin
 */
class com.mixmedia.utils.TextFieldUtils {
	/**
	 * @warning com.mixmedia.utils.TextFieldUtils.trim is slow if the string is too long 
	 * @param textField, string , [width, trimCharacter]
	 */
	static private var trimTextFieldProxy:TextField;
	static public function makeTextFieldProxy(){
		_root.createTextField('trimTextFieldProxy',52000,0,0,100,100);
		trimTextFieldProxy = _root.trimTextFieldProxy;
		trimTextFieldProxy.selectable = false;
		trimTextFieldProxy._visible = false;
	}

	static public function trim(txf:TextField,str:String,width:Number,trimCharacterLength:Number,isLiteral:Boolean):Boolean{
		if(isLiteral!=true){
			if(trimTextFieldProxy==null)TextFieldUtils.makeTextFieldProxy();
			if(width==null)width=txf._width;
			if(trimCharacterLength==null)trimCharacterLength=1;
			trimTextFieldProxy._width = txf._width;
			trimTextFieldProxy._height = txf._height;
			trimTextFieldProxy.wordWrap = txf.wordWrap;
			trimTextFieldProxy.autoSize = txf.autoSize;
			trimTextFieldProxy.setNewTextFormat(txf.getNewTextFormat());
			//check first time, if no need to trim, return false;
			txf.text = str;
			trimTextFieldProxy.text = txf.text;
			if(trimTextFieldProxy.textWidth<width)return false;
		}

		//remove last character until the width is suitable for display
		var displayStr = str.substr(0,str.length-trimCharacterLength)+"...";
		txf.text = displayStr;
		trimTextFieldProxy.text = txf.text;

		var textWidth = trimTextFieldProxy.textWidth;

 		if(textWidth>width){
 			trim(txf,str,width,trimCharacterLength+1,true);
 		}
 		return true;
	}
}